package com.app.video;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaFormat;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.util.Log;
import android.view.SurfaceHolder;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;

import com.app.G;
import com.app.util.Utils;
import com.app.util.Utils_Log;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by matengfei on 15/8/2.
 */
public class MyVideo {

    private String TAG = MyVideo.class.getSimpleName();


    MediaRecorder mMediaRecorder;  //录制
    boolean isRecord = false;

    MediaPlayer mPlayer; //播放
    SurfaceView view;

    public String filename = "";


    public String init(SurfaceView view, String filename) throws IOException { //

        String nowtime = Utils.getNowTime();
        filename += nowtime + "_" + filename;  // 使文件名不存在冲突的现象

        this.filename = G.PATH_AUDIO + "/" + filename;
        this.view = view;

        // 数值有要求不然没饭录制返回 E/MediaRecorder﹕ start failed: -19
        int width = 320; //view.getMeasuredWidth();
        int height = 240;//view.getMeasuredHeight();
        int frame = 20;

        Utils_Log.e(TAG, "filename:"+filename+" width: "+width+" height: "+height+" frame: "+frame);


          /* ①Initial：实例化MediaRecorder对象 */
        mMediaRecorder = new MediaRecorder();

        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

        //     THREE_GPP:    3gp格式，H263视频ARM音频编码
        //    MPEG-4:        MPEG4 media file format
        //    RAW_AMR:    只支持音频且音频编码要求为AMR_NB
        //    AMR_NB:
        //    ARM_MB:
        //    Default:
        // 3gp or mp4
        //
        //Android支持的音频编解码仅为AMR_NB； 支持对JPEG编解码；输出格式仅支持.3gp和.mp4
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        // 设置声音编码的格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        // 设置視頻/音频文件的编码：AAC/AMR_NB/AMR_MB/Default
        //    video: H.263, MP4-SP, or H.264
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); // 录制为h264有机器无法播放； http://blog.csdn.net/zhandoushi1982/article/details/5337797

        // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
        mMediaRecorder.setVideoSize(width, height);

        // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
        mMediaRecorder.setVideoFrameRate(frame);

        // 旋转90度
     //   mMediaRecorder.setOrientationHint(90);

         /* 设置输出文件的路径 */
        File file = new File(this.filename);
        if (file.exists()) {
            file.delete();
        }
        mMediaRecorder.setOutputFile(file.getAbsolutePath());


        // 预览
        mMediaRecorder.setPreviewDisplay(view.getHolder().getSurface()); //
        mMediaRecorder.prepare();

        return file.getAbsolutePath();
    }

    public void start_record(){

        if(!isRecord && mMediaRecorder!=null){

            try{
                mMediaRecorder.start();
                // 让录制状态为true
                isRecord = true;
            }catch(Exception ex){
                ex.printStackTrace();
                Utils_Log.e(TAG, "录制失败");
            }

        }


    }

    public String close_record(){

        if (mMediaRecorder != null) {
            isRecord = false;
            mMediaRecorder.release();
            mMediaRecorder = null;
        }

        return filename;

    }


    public byte[] getContent(){

        if(!filename.isEmpty()){

            byte[] bytes = Utils.readFile2Bytes(filename);
            return bytes;

        }

        return new byte[0];

    }



    public void play(){

        if(mPlayer == null)
            mPlayer = new MediaPlayer();

        try{
            mPlayer.reset();
            mPlayer.setDataSource(filename);
            //在这里我们指定MediaPlayer在当前的Surface中进行播放
            mPlayer.setDisplay(view.getHolder());
            //在指定了MediaPlayer播放的容器后，我们就可以使用prepare或者prepareAsync来准备播放了
            mPlayer.prepareAsync();
            mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mPlayer.start();
                }
            });
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stop_play();
                }
            });
        }catch(IOException e){
            Utils_Log.e(TAG, "播放失败");
        }

    }

    public  void play(SurfaceView view, String filename, MediaPlayer.OnCompletionListener completionListener){

        if(mPlayer == null)
            mPlayer = new MediaPlayer();

        try{
            mPlayer.reset();
            mPlayer.setDataSource(filename);
            //在这里我们指定MediaPlayer在当前的Surface中进行播放
            mPlayer.setDisplay(view.getHolder());
            //在指定了MediaPlayer播放的容器后，我们就可以使用prepare或者prepareAsync来准备播放了
            mPlayer.prepareAsync();
            mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mPlayer.start();
                }
            });
            if(completionListener != null)
                mPlayer.setOnCompletionListener(completionListener);
        }catch(IOException e){
            Utils_Log.e(TAG, "播放失败");
        }

    }

    public void play(SurfaceView view, String filename){
        play(view, filename, null);
    }


    public void stop_play(){
        if(mPlayer != null){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }

    }


    public boolean isPlaying(){
        if(mPlayer == null)
            return false;

        return mPlayer.isPlaying();
    }


    public void switch_pause(){
        if(mPlayer != null){
            if( mPlayer.isPlaying() )
                mPlayer.pause();
            else{
                mPlayer.seekTo(mPlayer.getCurrentPosition());
                mPlayer.start();
            }
        }


    }

    public void play_system(Activity activity, String filename){
        Uri uri = Uri.parse(filename);
        //调用系统自带的播放器
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, MediaFormat.MIMETYPE_VIDEO_H263);
        activity.startActivity(intent);

    }


    public void play_videoview(Activity activity, VideoView videoView, String filename){
        Uri uri = Uri.parse(filename);
        videoView.setMediaController(new MediaController(activity));
        videoView.setVideoURI(uri);
        videoView.start();
        videoView.requestFocus();

    }



    /* ok
    public void resume(){
        if(mPlayer != null && !mPlayer.isPlaying()){
            mPlayer.seekTo(mPlayer.getCurrentPosition());
            mPlayer.start();

        }
    }
    */





}
